﻿using System.Collections;
using System.Collections.Generic;
using SCore.Util;
using UnityEngine.AddressableAssets;
using UnityEngine.Networking;
using UnityEngine.ResourceManagement.AsyncOperations;

namespace Function.HotUpdate
{
    public class HotDownload : HotStep
    {
        private int _curDownCount = 0;
        //private string _dllLabel = "ag__hotupdatedll";

        public override HotState GetHotState()
        {
            return HotState.Download;
        }

        public HotDownload(HotContext hotContext, bool cb) : base(hotContext, cb)
        {
        }

        private IEnumerator CheckDownload()
        {
            if (_curDownCount < _hotContext._downLoadCount)
            {
                _curDownCount = _hotContext._downLoadCount + 1;
                yield return DownLoad();
            }
            else
            {
                SetSuccess(false);
                _hotContext.Error("下载失败", "重新尝试下载", (int)HotUpdateErrorType.DownloadFair);
                yield break;
            }
        }

        private IEnumerator DownLoad()
        {
            HotManager.Instance._commonTrace?.Invoke("down load start", null);
            //检测是否需要下载Dll
            AsyncOperationHandle<long> dllSizeCheck = Addressables.GetDownloadSizeAsync("Game.dll.bytes");
            yield return dllSizeCheck;
            if (dllSizeCheck.Status == AsyncOperationStatus.Succeeded)
            {
                _hotContext._updateDll = dllSizeCheck.Result > 0f;
            }
            else
            {
                _hotContext._updateDll = false;
            }

            Addressables.Release(dllSizeCheck);

            //下载
            var downHandle = Addressables.DownloadDependenciesAsync(
                _hotContext._updateKeys as IEnumerable<object>, Addressables.MergeMode.Union, false);
            while (!downHandle.IsDone)
            {
                var bar = downHandle.GetDownloadStatus().Percent;
                HotManager.Instance._downloadPercent?.Invoke(downHandle.GetDownloadStatus().Percent);
                _hotContext.Info("下载进度:", bar.ToString());
                yield return null;
            }

            yield return downHandle;
            if (downHandle.Status != AsyncOperationStatus.Succeeded)
            {
                Addressables.Release(downHandle);
                yield return CheckDownload();
            }
            else
            {
                HotManager.Instance._commonTrace?.Invoke("down load fair", null);
                SetSuccess(true);
                _hotContext.Info("HotDownload", "Down End");
                Addressables.Release(downHandle);
                yield return Finish();
            }
        }

        protected override IEnumerator OnExecute()
        {
            Addressables.WebRequestOverride = delegate(UnityWebRequest request)
            {
                // 有10M的资源，保险起见几乎不超时
                request.timeout = 180;
                BypassCertificate.Bypass(request);
            };

            _hotContext.Info("HotDownload", "Start");
            if (!_hotContext._needUpdate)
            {
                _hotContext._updateDll = false; //不需要下载的情况没有dll更新
                SetSuccess(true);
                yield return Finish();
                yield break;
            }

            var sizeHandle =
                Addressables.GetDownloadSizeAsync(_hotContext._updateKeys as IEnumerable<object>);
            yield return sizeHandle;
            if (sizeHandle.Result > 0)
            {
                HotManager.Instance._needUpdate?.Invoke();
                HotManager.Instance._resourceSize?.Invoke(sizeHandle.Result);
                yield return DownLoad();
            }
            else
            {
                _hotContext.Info("HotDownload", "Not Need Down End");
                SetSuccess(true);
                yield return Finish();
            }

            Addressables.Release(sizeHandle);
        }

        public override void ResNet()
        {
            _curDownCount = 0;
            HotManager.Instance.StartCoroutine(Execute());
        }

        public override void StopNet()
        {
            SetSuccess(false);
            HotManager.Instance.StopAllCoroutines();
        }
    }
}